<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>在线客服平台</title>
<link rel="stylesheet" href="/static/layim/css/layui.css">
<script src="/static/layim/layui.js"></script>
<script type="text/javascript" src="/static/js/jquery.min.js"></script>
<script type="text/javascript" src="/static/js/swfobject.js"></script>
<script type="text/javascript" src="/static/js/web_socket.js"></script>
</head>
<body>
<script>
	WEB_SOCKET_SWF_LOCATION = "/static/swf/WebSocketMain.swf";
    var
        ws,
        token     = '{$service_info.token}',
        user_name = '{$service_info.service_name}';
    var layer = layui.layer;
    /**
     * Notes:initServer Param
     * param: socket
     */
    function ini_set() {
        ws = new WebSocket("ws://" + document.domain + ":7272");
        ws.onopen = initServer;
        ws.onmessage = onMessage;
        ws.onclose = function () {
            console.log('进入客服系统失败');
        };
        ws.onerror = function () {
        	console.log('进入客服系统失败');
        };
    }
    /**
     * Notes:initServer
     * @throws \Exception
     */
    function initServer() {
        var init_data = '{"type":"service_login", "token":"' + token + '"}';
        ws.send(init_data);
    }

    /**
     * 接受消息方法
     * @param  {[type]} e [description]
     * @return {[type]}   [description]
     */
    function onMessage(e) {
    	var data = evil(e.data);
        if(data.type == 'friend')
        {
            layui.use('layim', function(layim){
                var layim = layui.layim;
                layim.getMessage(data);
            })
        }
	}

    //layim核心界面显示
    layui.use('layim', function(layim){
        var layim = layui.layim;
        //初始化聊天界面
        layim.config({
            init: {
              mine: {
                "username": ""+user_name+"" //我的昵称
                ,"id": ""+token+"" //我的ID
                ,"status": "online" //在线状态 online：在线、hide：隐身
                ,"avatar": "{$service_info.service_avatar}" //我的头像
              }
            },uploadImage: {
  				url: '/service_upload'
			}  
        });

        //监听发送消息
        layim.on('sendMessage', function(res){
            var mine = res.mine;
            var to = res.to;
            var message_data = {};
            message_data['type'] = 'service_message';
            message_data['receive_id'] = to.fromid;    //接收消息人的id
            message_data['from_name']  = user_name;        //发送人名称
            message_data['from_head']  = '{$service_info.service_avatar}'; //发送人头像
            message_data['message_content'] = mine.content; 
            message_data['token']    = token; 
            var json_message_data = JSON.stringify( message_data );
            ws.send(json_message_data);
        })
    });

	function evil(fn) {
    	var Fn = Function;  
    	return new Fn('return ' + fn)();
	}

    ini_set();
</script>
</body>
</html>